import "./userinfo.scss"
import service from "@@/services/user.service"
import React, { useCallback, useEffect, useState } from "react"
import NavLayout from "@@/components/layout/nav.layout"
import citytreeConst from "@@/constant/citytree.const"
import Ticon from "@@/t-ui/icon.tui"
import TInput from "@@/t-ui/input.tui"
import { BaseEventOrig, Image, Picker, Text, View } from "@tarojs/components"
import { PickerMultiSelectorProps } from "@tarojs/components/types/Picker"
import { useDidHide, useDidShow, useReady, getStorageSync, navigateTo } from "@tarojs/taro"
import TButton from "@@/t-ui/button.tui"
import TCheckBox from "@@/t-ui/checkbox.tui"
import TToast from "@@/t-ui/toast.tui"

//邮箱校验
const emailRegexp = /^([0-9A-Za-z]+|[0-9A-Za-z]+\.[0-9A-Za-z]+)(@)([0-9A-Za-z]+\.)([A-z]+)$/;
interface cityData {
  code: string
  name: string
  children?: cityData[]
}
const RegisterPage = () => {
  const [userId, setUserId] = useState<number>("")//id
  const [name, setName] = useState<string>("")//用户名
  const [email, setEmail] = useState<string>("")//邮箱
  const [company, setCompany] = useState<string>("")//单位信息
  const [mobile, setMobile] = useState<string>("")//手机号

  const [cityValue, setCityValue] = useState<(number)[]>([0, 0, 0])
  const [rangeValue, setRangeValue] = useState<number[]>([0, 0, 0])

  const [isOpened, setIsOpened] = useState<boolean>(false)//轻提示开关
  const [toastMsg, setToastMsg] = useState<string>("")//轻提示内容

  useEffect(() => {
    // chooseImage 上传头像图片
    //判断是否h5端
    if (TARO_ENV === "h5") {
      // console.log(getStorageSync("token"))
      if (getStorageSync("token")) {
        service.getUserInfo().then(res => {
          if (res.code === 200) {
            // console.log(res)
            const data = res.data;
            setUserId(data.id);
            setName(data.name);
            setEmail(data.email);
            setCompany(data.company);
            setMobile(data.mobile);
            initArea(data.province, data.city, data.area)
          } else {
            openToast(res.msg)
            return false
          }
        })
      }
    }
  }, [])

  //选中省市区
  const initArea = (province: string, city: string, area: string) => {
    let curProvince, curProvinceIndex, curCity, curCityIndex, curAreaIndex;
    citytreeConst.forEach((item, index) => {
      if (item.code === province) {
        curProvince = item;
        curProvinceIndex = index;
      }
    })
    curProvince.children.forEach((item, index) => {
      if (item.code === city) {
        curCity = item;
        curCityIndex = index;
      }
    })
    curCity.children.forEach((item, index) => {
      if (item.code === area) {
        curAreaIndex = index;
      }
    })
    // console.log(curProvince, curProvinceIndex, curCity, curCityIndex, curAreaIndex)
    setCityValue([curProvinceIndex, curCityIndex, curAreaIndex]);
    setRangeValue([curProvinceIndex, curCityIndex, curAreaIndex]);
  }
  const onColumnChange = useCallback(
    (e: BaseEventOrig<PickerMultiSelectorProps.onColumnChangeEvnetDetail>) => {
      const { column, value } = e.detail
      const newData = [...rangeValue]
      for (let index = column; index < newData.length; index++) {
        newData.splice(index, 1, index === column ? value : 0)
      }
      setRangeValue(newData)
    },
    [rangeValue]
  )
  const onChange = useCallback((e: BaseEventOrig<PickerMultiSelectorProps.onChangeEventDetail>) => {
    const { value } = e.detail
    setCityValue(value)
  }, [])
  const getItems = useCallback(
    (data: cityData[], index: number, result: (cityData | null)[]): (cityData | null)[] => {
      return index < cityValue.length
        ? cityValue[index] !== null
          ? data[cityValue[index]].children
            ? getItems(
              data[cityValue[index]].children!,
              index + 1,
              result.concat([
                {
                  name: data[cityValue[index]].name,
                  code: data[cityValue[index]].code
                }
              ])
            )
            : result.concat([
              {
                name: data[cityValue[index]].name,
                code: data[cityValue[index]].code
              }
            ])
          : getItems([], index + 1, result.concat([null]))
        : result
    },
    [cityValue]
  )

  const editUserInfo = () => {
    if (TARO_ENV === "h5") {
      if (!emailRegexp.test(email)) {
        openToast("邮箱格式不正确！")
        return false
      }
      const params = {
        id: userId,
        name,
        email,
        company,
        province: citytreeConst[cityValue[0]]?.code,
        provinceName: citytreeConst[cityValue[0]]?.name,
        city: citytreeConst[cityValue[0]]?.children[cityValue[1]]?.code,
        cityName: citytreeConst[cityValue[0]]?.children[cityValue[1]]?.name,
        area: citytreeConst[cityValue[0]]?.children[cityValue[1]]?.children[cityValue[2]].code,
        areaName: citytreeConst[cityValue[0]]?.children[cityValue[1]]?.children[cityValue[2]].name,
      }
      // console.log(params)
      service.updateUserInfo(params).then(res => {
        if (res.code === 200) {
          openToast("保存用户信息成功");
          navigateTo({
            url: "/pages/mine/mine"
          })
        }
      })
    }
  }

  const openToast = (str: string) => {
    setToastMsg(str)
    setIsOpened(true)
    setTimeout(() => {
      setIsOpened(false)
    }, 500)
  }
  return (
    <NavLayout border leftIconType="chevron-left" color="#141414" id="userinfoPage">

      <View className="userinfo">
        <View className="form">
          <View className="input-item">
            <TInput border={false} name="name" type="text" defaultVal={name} placeholder="请输入姓名" onChange={v => {
              setName(v)
              return v
            }} />
          </View>
          <View className="input-item">
            <TInput border={false} name="email" type="text" defaultVal={email} placeholder="请输入邮箱" onChange={v => {
              setEmail(v)
              return v
            }} />
          </View>
          <View className="input-item">

            <TInput
              border={false}
              name="company"
              type="text"
              defaultVal={company}
              placeholder="请输入单位信息"
              onChange={v => {
                setCompany(v)
                return v
              }}
            />
          </View>
          <Picker
            mode="multiSelector"
            range={[
              citytreeConst,
              citytreeConst[rangeValue[0]].children,
              citytreeConst[rangeValue[0]].children[rangeValue[1]].children
            ]}
            rangeKey="name"
            value={rangeValue}
            onChange={onChange}
            onColumnChange={onColumnChange}
          >
            <View className="select-city">
              {getItems(citytreeConst, 0, []).map((m, i) => {
                return (
                  <View className="input-item" key={i}>
                    <Text className="city-name">{m ? m.name : `选择${["省", "市", "区"][i]}`}</Text>
                    <Ticon value="chevron-down" size={0} />
                  </View>
                )
              })}
            </View>
          </Picker>
          <View className="input-item">
            <TInput disabled border={false} name="mobile" type="text" defaultVal={mobile} title="手机" onChange={() => { }} />
          </View>
          <View className="form-btn">
            <TButton type="primary" onClick={editUserInfo}>保存</TButton>
          </View>

        </View>

        <View className="bg" />
        <TToast isOpened={isOpened} text={toastMsg} />
      </View>
    </NavLayout>
  )
}
export default RegisterPage
